package com.hspedu.sqlsession;

import com.hspedu.entity.Monster;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class HspExecutor implements Executor{
    private HspConfiguration hspConfiguration = new HspConfiguration();
    @Override
    public <T> T query(String sql, Object parameter) {
        Connection connection = getConnection();
        ResultSet set = null;
        PreparedStatement pre = null;
        try{
            pre = connection.prepareStatement(sql);
            //设置参数，如果参数多，可以使用数组来处理
            pre.setString(1,parameter.toString());
            set = pre.executeQuery();
            //这里可以使用 ,一套反射机制来创建, 后面可以优 化灵活.
            Monster monster = new Monster();
            //遍历结果集
            //光标向下移动一行，并且判断当前行是否有数据
            while (set.next()){
                monster.setId(set.getInt("id"));
                monster.setName(set.getString("name"));
                monster.setEmail(set.getString("email"));
                monster.setAge(set.getInt("age"));
                monster.setGender(set.getInt("gender"));
                monster.setBirthday(set.getDate("birthday"));
                monster.setSalary(set.getDouble("salary"));
            }
            return (T)monster;

        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            try {
                if (set != null){
                    set.close();
                }
                if(pre!=null){
                    pre.close();
                }
                if (connection != null) {
                    connection.close();
                }
            }catch (Exception e2){
                e2.printStackTrace();
            }
        }
        return null;
    }

    private Connection getConnection(){
        try{
            Connection connection = hspConfiguration.build("hsp_mybatis.xml");
            return connection;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
